package com.csist.dao;

import com.csist.model.Message;
import com.csist.util.JDBCUtil;

import java.sql.*;
import java.util.ArrayList;

/**
 * @ClassName MessageDao
 * @Description TODO
 * @Author User
 * @Date 2021/6/14 20:38
 * @ModifyDate 2021/6/14 20:38
 * @Version 1.0
 */
public class MessageDao {
    /**
     * 消息记录存储到数据库
     * @param senderId 发送者id
     * @param receiverId 接收者id
     * @param msg 消息内容
     */
    public void sendMsg(int senderId,int receiverId, String msg){
        Connection conn = JDBCUtil.getConnection();
        PreparedStatement ps = null;
        String sql = "insert into message value(default,?,?,?,?,false )";
        try {
            ps = conn.prepareStatement(sql);
            ps.setInt(1,senderId);
            ps.setString(2,msg);
            ps.setInt(3,receiverId);
            ps.setDate(4,new Date(new java.util.Date().getTime()));
            ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtil.close(conn,ps);
        }

    }

    /**
     * 返回未被接收的消息对象集合
     * @param receiver 接收者id
     * @return ArrayList<Message> 未被接收的消息对象集合
     */
    public ArrayList<Message> getMessage(int receiver){
        Connection conn = JDBCUtil.getConnection();
        PreparedStatement statement = null;
        String sql = "select * from message where state = false and receiver = ?";
        ResultSet rs = null;
        ArrayList<Message> messages = new ArrayList<>();
        try {
            statement = conn.prepareStatement(sql);
            statement.setInt(1,receiver);
            rs = statement.executeQuery();
            while(rs.next()){
                Message message = new Message();
                message.setSender(rs.getInt(2));
                message.setMsg(rs.getString(3));
                message.setReceiver(rs.getInt(4));
                message.setSendtime(rs.getDate(5));
                message.setState(rs.getBoolean(6));
                messages.add(message);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtil.close(conn,statement,rs);
        }
        return messages;

    }

    /**
     * 根据接收者id设置消息为已被接收状态
     * @param receiver 消息的接收者id
     */
    public void setStateTrue(int receiver){
        Connection conn = JDBCUtil.getConnection();
        PreparedStatement statement = null;
        String staticSql = "update message set state = true where state = false and receiver = ?";
        try {
            statement = conn.prepareStatement(staticSql);
            statement.setInt(1,receiver);
            statement.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtil.close(conn,statement);
        }
    }
}
